﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTracker.Model;
using System.Runtime.Serialization.Json;
using AutoMapper;

namespace ScrumTrackerAjax.Areas.API.Controllers
{
    public class ProductsController : AbstractController
    {
        //
        // GET: /API/Products/

        public ActionResult List()
        {
            var dto = new Product.DTO();
            var products = Product.Search(includeHidden: true);
            Mapper.CreateMap<Product, Product.DTO>();
            return JsonNet(Mapper.Map<List<Product.DTO>>(products), JsonRequestBehavior.AllowGet);//, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult List(Product.DTO model)
        {
            if (ModelState.IsValid)
            {
                var product = Product.Add(model);
                Mapper.CreateMap<Product, Product.DTO>();
                model = Mapper.Map<Product.DTO>(product);
                return JsonNet(model, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var validationResponse = new { ValidationMessages = ModelState.Where(kvp => kvp.Value.Errors != null && kvp.Value.Errors.Count > 0).Select(kvp => new { Property = kvp.Key, Errors = kvp.Value.Errors.Select(e => e.ErrorMessage) }) };
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                return JsonNet(validationResponse, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Resource(int id)
        {
            Mapper.CreateMap<Product, Product.DTO>();
            return JsonNet(new { Success = true, model = Mapper.Map<Product.DTO>(Product.Find(id)) }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult Resource(int id, Product.DTO model)
        {
            if (ModelState.IsValid)
            {
                return JsonNet(model, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var validationResponse = new { Success = false, ValidationMessages = ModelState.Where(kvp => kvp.Value.Errors.Any()).Select(kvp => new { Property = kvp.Key, Errors = kvp.Value.Errors.Select(e => e.ErrorMessage) }) };
                return JsonNet(validationResponse, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpDelete]
        public ActionResult Resource(int id, string delete)
        {
            var product = Product.Find(id);
            product.IsDeleted = true;
            ScrumTrackerEntities.Instance.SaveChanges();
            Mapper.CreateMap<Product, Product.DTO>();
            return JsonNet(Mapper.Map<Product.DTO>(product), JsonRequestBehavior.AllowGet);
        }
    }
}
